package io.seata.samples.tcc.springboot.dubbo.service;

import io.seata.samples.tcc.springboot.dubbo.action.TccActionOne;
import io.seata.samples.tcc.springboot.dubbo.action.TccActionTwo;
import io.seata.samples.tcc.springboot.dubbo.model.User;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * The type Tcc transaction service.
 *
 * @author louis
 */
@Service
public class TccTransactionService {

    @Resource
    private TccActionOne tccActionOne;
    @Resource
    private TccActionTwo tccActionTwo;
    @Reference(version = "1.0.0", group = "tcc")
    private UserService userService;

    /**
     * 测试分布式事务提交示例
     *
     * @return string string
     */
    @GlobalTransactional
    public String testCommit() {
        // 第一个TCC 事务参与者
        String result = tccActionOne.prepare("action-one-commit").getMessage();
        // 第二个TCC 事务参与者
        result = result + "\n" + tccActionTwo.prepare("action-two-commit").getMessage();
        // 数据库操作
        userService.save(getUser());
        return result;
    }

    /**
     * 测试分布式事务回滚示例
     * @return string string
     */
    @GlobalTransactional
    public String testRollback() {
        //第一个TCC 事务参与者
        String result = tccActionOne.prepare("action-one-rollback").getMessage();
        // 第二个TCC 事务参与者
        result = result + "\n" + tccActionTwo.prepare("action-two-rollback").getMessage();
        // 数据库操作
        userService.save(getUser());
        throw new RuntimeException(result);
    }

    private User getUser() {
        User user = new User();
        user.setUsername("王五");
        user.setPassword("888888");
        user.setRealname("ww");
        return user;
    }
}
